package com.jiazhong.basic.shuxin.net;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class DemoE1 {

    @SneakyThrows
    public static void main(String[] args) {
        ServerSocket serverSocket = new ServerSocket(8889);
        Socket socket = serverSocket.accept();
        new Thread(() -> {
            try {
                OutputStream outputStream = socket.getOutputStream();
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    System.out.print("Input:");
                    String message = scanner.next();
                    outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                    if ("bye".equals(message)) {
                        break;
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();

       new Thread(() -> {
           try {
               InputStream in = socket.getInputStream();
               byte[] bytes = new byte[1024];
               while (true) {
                   int len = in.read(bytes);
                   String message = new String(bytes, 0, len);
                   System.out.println("客户端说："+message);
                   if ("bye".equals(message)) {
                       break;
                   }
               }
           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }).start();

    }
}
